package com.kuang.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

// 枚举避免单例被反射破坏  enum本身也是一个Class类
public enum EnumSingle {
    // 实例
    INSTANCE;

    // 获取实例方法
    public static EnumSingle getInstance(){
        return INSTANCE;
    }

    // 枚举私有构造器
    private EnumSingle(){}
}

class Test{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //EnumSingle instance1 = EnumSingle.INSTANCE;
        //EnumSingle instance2 = EnumSingle.INSTANCE;
        //EnumSingle instance3 = EnumSingle.getInstance();
        //System.out.println(instance1);//INSTANCE
        //System.out.println(instance2);//INSTANCE
        //System.out.println(instance3);//INSTANCE

        // 测试反射是否能破坏枚举单例，预期：如果通过反射创建多个实例，会抛出异常
        EnumSingle instance1 = EnumSingle.INSTANCE;
        //Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor();  //报错：EnumSingle.<init>() NoSuchMethodException，不能抛出想要的异常
        Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);  //IllegalArgumentException: Cannot reflectively create enum objects
        declaredConstructor.setAccessible(true);  // 设置为可访问
        EnumSingle instance2 = declaredConstructor.newInstance();
        System.out.println(instance1);
        System.out.println(instance2);   //不能反射地创建枚举对象
    }
}
